package com.jnchen.jwt.impl;

import com.jnchen.jwt.api.JwtInterface;
import com.jnchen.jwt.entity.User;
import com.jnchen.jwt.util.RsaUtil;
import io.jsonwebtoken.*;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;
import java.util.List;

/**
 * jjwt实现
 *
 * @author jnchen
 * @date 2020/10/30 10:26
 */
public class JjwtImpl implements JwtInterface {
    private static final PrivateKey PRIVATE_KEY;
    private static final PublicKey PUBLIC_KEY;

    static {
        KeyPair pair = RsaUtil.getRsaKey();
        PRIVATE_KEY = pair.getPrivate();
        PUBLIC_KEY = pair.getPublic();
    }

    @Override
    public String createJwt(User user, long expireIn) {
        return Jwts.builder()
                .claim("id", user.getId())
                .claim("name", user.getName())
                .claim("operations", user.getOperations())
                .setExpiration(new Date(System.currentTimeMillis() + expireIn))
                .signWith(SignatureAlgorithm.RS512, PRIVATE_KEY).compact();
    }

    @SuppressWarnings("unchecked")
    @Override
    public User parseJwt(String token) {
        Jws<Claims> jwt = Jwts.parser().setSigningKey(PUBLIC_KEY).parseClaimsJws(token);
        User user = new User();
        user.setId(jwt.getBody().get("id", Integer.class));
        user.setName(jwt.getBody().get("name", String.class));
        user.setOperations(jwt.getBody().get("operations", List.class));
        return null;
    }

    @Override
    @SuppressWarnings({"rawtypes","unused"})
    public boolean checkJwt(String token) {
        JwtParser parser = Jwts.parser();
        try {
            Jwt<Header, Claims> jwt = parser.setSigningKey(PUBLIC_KEY).parseClaimsJwt(token);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
